import tsc from '../utils/tsc.js';
import esc from '../utils/esc.js';

// 打印程序begin---------------------------------
  
  /**
   * android 6.0以上需授权地理位置权限
   */
  var checkPemission = function(that) {
    var systemInfo = wx.getSystemInfoSync();
    var platform = systemInfo.platform;
    if (platform == "ios") {
		getBluetoothDevices(that)
    } else if (platform == "android") {
      let system = systemInfo.system;
      let system_no = system.replace('android', '');
      system_no = system.replace('Android', '');
      if (Number(system_no) > 5) {
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                complete: function (res) {
                  getBluetoothDevices(that)
                }
              })
            } else {
              getBluetoothDevices(that)
            }
          }
        })
      }
    }
  }

  /**
   * 获取蓝牙设备信息
   */
  var getBluetoothDevices = function (that) {
    console.log("start search")
    wx.showLoading({
      title: '搜索中',
    })
    that.setData({
      isScanning: true
    })
    wx.startBluetoothDevicesDiscovery({
      success: function (res) {
        setTimeout(function () {
          wx.getBluetoothDevices({
            success: function (res) {
              var devices = []
              var num = 0
              for (var i = 0; i < res.devices.length; ++i) {
                if (res.devices[i].name != "未知设备") {
                  devices[num] = res.devices[i]
                  num++
                }
              }
              that.setData({
                devicesList: devices,
                isScanning: false
              })
              wx.hideLoading()
              wx.stopPullDownRefresh()
            },
          })
        }, 3000)
      },
    })
  }

  /**
   * 开始连接蓝牙设置
   */
  var connectBluetoothSettings =  function (app, that, e) {
    let index = e.currentTarget.dataset.index;
    let deviceId = that.data.devicesList[index].deviceId;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        //console.log(res)
      },
    })
    that.setData({
      serviceId: 0,
      writeCharacter: false,
      readCharacter: false,
      notifyCharacter: false
    })
    wx.showLoading({
      title: '正在连接',
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        app.globalData.bluetoothDeviceId = deviceId
        getBLEDeviceServices(app, that);
        wx.showLoading({
          title: '连接好可以打印',
        })
      },
      fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '连接失败',
        })
        wx.hideLoading()
      },
      complete: function (e) {
        //console.log(e)
      }
    })
  }

  /**
   * 获取蓝牙设备所有服务
   */
  var getBLEDeviceServices = function (app, that) {
    console.log(app.globalData.bluetoothDeviceId)
    wx.getBLEDeviceServices({
      deviceId: app.globalData.bluetoothDeviceId,
      success: function (res) {
        that.setData({
          services: res.services
        })
        getBLEDeviceCharacteristics(app, that)
      },
      fail: function (e) {
        console.log(e)
      },
      complete: function (e) {
        //console.log(e)
      }
    })
  }

  /**
   * 获取蓝牙设备某个服务中所有特征值
   */
  var getBLEDeviceCharacteristics = function (app, that) {
    var list = that.data.services
    var num = that.data.serviceId
    var write = that.data.writeCharacter
    var read = that.data.readCharacter
    var notify = that.data.notifyCharacter
    wx.getBLEDeviceCharacteristics({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: list[num].uuid,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; ++i) {
          var properties = res.characteristics[i].properties
          var item = res.characteristics[i].uuid
          if (!notify) {
            if (properties.notify) {
              app.globalData.notifyCharaterId = item
              app.globalData.notifyServiceId = list[num].uuid
              notify = true
            }
          }
          if (!write) {
            if (properties.write) {
              app.globalData.writeCharaterId = item
              app.globalData.writeServiceId = list[num].uuid
              write = true
            }
          }
          if (!read) {
            if (properties.read) {
              app.globalData.readCharaterId = item
              app.globalData.readServiceId = list[num].uuid
              read = true
            }
          }
        }
        if (!write || !notify || !read) {
          num++
          that.setData({
            writeCharacter: write,
            readCharacter: read,
            notifyCharacter: notify,
            serviceId: num
          })
          if (num == list.length) {
            wx.showModal({
              title: '提示',
              content: '找不到该读写的特征值',
            })
          } else {
            getBLEDeviceCharacteristics(app, that)
          }
        } else {
          notifyBLECharacteristicValueChange(app)
        }
      },
      fail: function (e) {
        console.log(e)
      },
      complete: function (e) {
        //console.log("write:" + app.globalData.writeCharaterId)
        //console.log("read:" + app.globalData.readCharaterId)
        //console.log("notify:" + app.globalData.notifyCharaterId)
      }
    })
  }

  /**
   * 启用低功耗蓝牙设备特征值变化时的 notify 功能
   */
  var notifyBLECharacteristicValueChange = function (app) {
    //console.log("deviceId:" + app.globalData.bluetoothDeviceId)
    //console.log("serviceId:" + app.globalData.notifyServiceId)
    //console.log("notifyCharaterId:" + app.globalData.notifyCharaterId)
    wx.hideLoading();
    wx.notifyBLECharacteristicValueChange({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: app.globalData.notifyServiceId,
      characteristicId: app.globalData.notifyCharaterId,
      state: true,
      success: function(res) {
        wx.onBLECharacteristicValueChange(function(r) {
          //console.log('onBLECharacteristicValueChange=', r);
        })
      },
      fail: function(e) {
        console.log('fail', e)
      },
      complete: function(e) {
        //console.log('complete', e)
      }
    })
  }

  /**
   * 标签模式
   */
  var labelTest = function(app, that) {
    var command = tsc.jpPrinter.createNew()
    command.setSize(70, 50) //纸宽度70，高度50
    command.setGap(0)
    command.setCls() //需要设置这个，不然内容和上一次重复
    // 10起始位置,10行距,TSS24.BF2字体,1字与字之间的间距,1字体大小,最后一个打印内容
    command.setText(10, 10, "TSS24.BF2", 2, 2, '同城速运 210920000003')
    command.setText(10, 70, "TSS24.BF2", 1, 1, '收方：尚未来 15655555555')
    command.setText(10, 110, "TSS24.BF2", 1, 1, '收方地址：安徽合肥市')
    command.setText(10, 150, "TSS24.BF2", 1, 1, '寄放：刘晓峰 17788888888')
    command.setText(10, 190, "TSS24.BF2", 1, 1, '货物名称：猕猴桃 运费：100.00')
    command.setText(10, 230, "TSS24.BF2", 1, 1, '数量：10箱')
    command.setText(10, 270, "TSS24.BF2", 1, 1, '日期：2021-09-22 15:23:50')
    //command.setText(10, 40, "TSS24.BF2", 1, 2, "蓝牙热敏标签打印测试2")
    command.setPagePrint()
    prepareSend(app, that, command.getData())
  }

  // 打印标签
  var printLable = function(app, that, print_content) {
    var command = tsc.jpPrinter.createNew()
    command.setSpeed(0)
    command.setSize(70, 48) //纸宽度70，高度50
    command.setGap(0)
    command.setCls() //需要设置这个，不然内容和上一次重复
    // 10起始位置,10行距,TSS24.BF2字体,1字与字之间的间距,1字体大小,最后一个打印内容
    command.setText(10, 0, "TSS24.BF2", 2, 2, print_content[0])
    command.setText(10, 60, "TSS24.BF2", 1, 1, print_content[1])
    command.setText(10, 100, "TSS24.BF2", 1, 1, print_content[2])
    command.setText(10, 140, "TSS24.BF2", 1, 1, print_content[3])
    command.setText(10, 180, "TSS24.BF2", 1, 1, print_content[4])
    command.setText(10, 220, "TSS24.BF2", 1, 1, print_content[5])
    command.setText(10, 260, "TSS24.BF2", 1, 1, print_content[6])
    command.setText(10, 300, "TSS24.BF2", 1, 1, print_content[7]) 
    command.setPagePrint()
    prepareSend(app, that, command.getData())
  }

  /**
   * 准备发送数据
   */
  var prepareSend = function(app, that, buff) { 
    //console.log('buff', buff)
    var time = that.data.oneTimeData
    var looptime = parseInt(buff.length / time);
    var lastData = parseInt(buff.length % time);
    that.setData({
      looptime: looptime + 1,
      lastData: lastData,
      currentTime: 1,
    })
    Send(app, that, buff)
  }

  /**
   * 查询打印机状态
   */
  var queryPrinterStatus = function() {
    var command = esc.jpPrinter.Query();
    command.getRealtimeStatusTransmission(1);
    this.setData({
      returnResult: "查询成功"
    })
  }

  /**
   * 分包发送
   */
  var Send = function(app, that, buff) {
    var currentTime = that.data.currentTime;
    var loopTime = that.data.looptime;
    var lastData = that.data.lastData;
    var onTimeData = that.data.oneTimeData;
    var printNum = that.data.printNum; //打印多少份
    var currentPrint = that.data.currentPrint;
    var buf
    var dataView
    if (currentTime < loopTime) {
      buf = new ArrayBuffer(onTimeData)
      dataView = new DataView(buf)
      for (var i = 0; i < onTimeData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    } else {
      buf = new ArrayBuffer(lastData)
      dataView = new DataView(buf)
      for (var i = 0; i < lastData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    }
    console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength);
    console.log("deviceId:" + app.globalData.bluetoothDeviceId)
    console.log("serviceId:" + app.globalData.writeServiceId)
    console.log("characteristicId:" + app.globalData.writeCharaterId)
    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: app.globalData.writeServiceId,
      characteristicId: app.globalData.writeCharaterId,
      value: buf,
      success: function(res) {
        console.log('写入成功', res)
      },
      fail: function(e) {
        console.error('写入失败', e)
      },
      complete: function() {
        currentTime++
        if (currentTime <= loopTime) {
          that.setData({
            currentTime: currentTime
          })
          Send(app, that, buff)
        } else {
          if (currentPrint == printNum) {
            that.setData({
              looptime: 0,
              lastData: 0,
              currentTime: 1,
              isReceiptSend: false,
              isLabelSend: false,
              currentPrint: 1
            })
          } else {
            currentPrint++
            that.setData({
              currentPrint: currentPrint,
              currentTime: 1,
            })
            console.log("开始打印")
            Send(app, that, buff)
          }
        }
        //console.log('打印完成')
      }
    })
  }
  
  /**
   * 蓝牙搜索
   */
  var searchBluetooth = function (that) {
    //判断蓝牙是否打开
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.getBluetoothAdapterState({
          success: function (res) {
            if (res.available) {
              if (res.discovering) {
                wx.stopBluetoothDevicesDiscovery({
                  success: function (res) {
                    //console.log(res)
                  }
                })
              }
              checkPemission(that)
            } else {
              wx.showModal({
                title: '提示',
                content: '请开启手机蓝牙后再试',
              })
            }
          },
        })
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '蓝牙初始化失败，请打开蓝牙',
        })
      }
    })
  }
  // -end---------------------------------
  
module.exports = {
  searchBluetooth: searchBluetooth,
  connectBluetoothSettings: connectBluetoothSettings,
  labelTest: labelTest,
  printLable: printLable
}